package hotel.controller.user;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import hotel.common.Md5;
import hotel.common.MsgBox;
import hotel.modal.User;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.scene.control.ChoiceBox;

public class UserDetailsController {
	@FXML private Button btnChange;
	@FXML private Button btnCancel;
	@FXML private TextField userNameField;
	@FXML private TextField employeeIdField;
	@FXML private TextField passwordField;
	@FXML private ChoiceBox<String> adminCh;
	protected User user = null;
	
	@FXML
    public void initialize() {
		// 设置一个监听，输入框只允许输入数字
		employeeIdField.textProperty().addListener(new ChangeListener<String>() {
			@Override
			public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
				if (!newValue.matches("\\d*")) { employeeIdField.setText(newValue.replaceAll("[^\\d]", "")); }
			}
		});
	}

	// Event Listener on Button[#btnChange].onAction
	@FXML
	public void onBtnChange(ActionEvent event) {
		Boolean pass = true;
		String userName = userNameField.getText().trim();
		String employeeId = employeeIdField.getText().trim();
		String password = passwordField.getText();
		Boolean admin = false;
		if(userName.length() > 20) {
			pass = false;
			MsgBox.showErrorDialog("错误", null, "登录名过长");
			userNameField.requestFocus();
		}
		if(adminCh.getSelectionModel().getSelectedItem().equals("是")) { 
			admin = true;
		}
		else admin = false;
		
		if(pass) {
			user.setUserName(userName);
			if(!employeeId.equals("")) user.setEmployeeId(Integer.parseInt(employeeId));
			user.setPassword(Md5.getMD5(password));
			user.setAdmin(admin);
			user.setModified(true);
			closeWindow();
		}else {
			pass = true;
		}
		
	}
	// Event Listener on Button[#btnCancel].onAction
	@FXML
	public void onBtnCancel(ActionEvent event) {
		user.setModified(false);
		closeWindow();
	}
	
	@FXML
	public void onPasswordFieldMouseClicked(MouseEvent event) {
		passwordField.selectAll();
	}
	
	private void closeWindow() {
		Stage stage = (Stage) btnCancel.getScene().getWindow();
		stage.close();
	}
	
	public void initUser(User user) {
		this.user = user;
		if(user != null) {
			userNameField.setText(user.getUserName());
			int employeeId = user.getEmployeeId();
			if(employeeId == -1) employeeIdField.setText("");
			else employeeIdField.setText(String.valueOf(employeeId));
			passwordField.setText(user.getPassword());
			if(user.isAdmin()) adminCh.getSelectionModel().select("是");
			else adminCh.getSelectionModel().select("否");
		}
	}
}
